package com.mulder.study.netty.client.demo;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;

import com.mulder.study.netty.NettyCommonUtil;
import com.mulder.study.netty.client.MulderNettyCommonClientHandler;

public class WebClientTestHandler extends MulderNettyCommonClientHandler {
	private static Logger logger = Logger.getLogger(MulderNettyCommonClientHandler.class);
	
	private String httpHost;
	private String httpUri;
	
	static final String[] HTTP_CLI_HEADERS = {
            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
            ,"Accept-Charset: utf-8;q=0.7,*;q=0.3"
            ,"Connection: close"
            ,"User-Agent: Netty-Test-mulder-Client-v0.1"
        };
	
        public WebClientTestHandler(String httpHost, String httpUri)
        {
            super();
            this.httpHost = httpHost;
            this.httpUri = httpUri;
        }

        public void startupAction(ChannelHandlerContext ctx, ChannelStateEvent e)
            throws Exception
        {
            String buffer = "GET "+ this.httpUri +" HTTP/1.0\r\n";
            
            buffer += "Host: " + this.httpHost + "\r\n";
            for(String h : HTTP_CLI_HEADERS) 
            {
                buffer += (h + "\r\n");
            }
            buffer += "\r\n";
                
            logger.info("httpClientSendBuffer:" + buffer);
            
            NettyCommonUtil.sendResponse (e.getChannel(), buffer.getBytes());
        }


        @Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception 
	{
	    super.exceptionCaught(ctx, e);
	    e.getChannel().close();
	}



	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception 
	{
	    super.messageReceived(ctx, e);
		
	    ChannelBuffer request  = (ChannelBuffer)e.getMessage();
	    byte[] message = request.readBytes(request.readableBytes()).array();
		
	    logger.info("read=>" + new String(message, "utf-8"));
	}
	
	
	
	

}
